package me.zhengjie.minbearwcs.serivce.mission.generate.rework;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.minbearwcs.dao.mission.inf.WcsMissionDao;
import me.zhengjie.minbearwcs.dao.outbound.inf.OutboundDao;
import me.zhengjie.minbearwcs.dao.rework.inf.ReworkOrderDetailDao;
import me.zhengjie.minbearwcs.dao.storage.inf.LargeStorageDao;
import me.zhengjie.minbearwcs.dao.storage.inf.SmallStorageDao;
import me.zhengjie.minbearwcs.dao.storage.inf.StorageDao;
import me.zhengjie.minbearwcs.entity.DTO.outbound.wcs.MediumStockUp;
import me.zhengjie.minbearwcs.entity.DTO.transfer.Tuple;
import me.zhengjie.minbearwcs.entity.PO.wcs.mission.WcsMission;
import me.zhengjie.minbearwcs.entity.PO.wcs.mission.status.OutboundAfterSortMissionStatus;
import me.zhengjie.minbearwcs.entity.PO.wcs.mission.status.ReworkProductLineStatus;
import me.zhengjie.minbearwcs.entity.PO.wcs.mission.type.MissionType;
import me.zhengjie.minbearwcs.entity.PO.wcs.outbound.common.OutboundContentPool;
import me.zhengjie.minbearwcs.entity.PO.wcs.outbound.record.OutboundTaskRecord;
import me.zhengjie.minbearwcs.entity.PO.wcs.outbound.stockUp.OutboundStockUpRecord;
import me.zhengjie.minbearwcs.entity.PO.wcs.outbound.stockUp.PalletMediumStorageSearchPo;
import me.zhengjie.minbearwcs.entity.PO.wcs.rework.ReworkOrderDetail;
import me.zhengjie.minbearwcs.entity.PO.wcs.rework.status.ReworkOrderDetailStatus;
import me.zhengjie.minbearwcs.entity.PO.wcs.storage.LargeStorage;
import me.zhengjie.minbearwcs.entity.PO.wcs.storage.SmallStorage;
import me.zhengjie.minbearwcs.entity.PO.wcs.storage.type.StorageType;
import me.zhengjie.minbearwcs.serivce.mission.generate.MissionGenerator;
import me.zhengjie.minbearwcs.serivce.mission.generate.type.MissionGenType;
import me.zhengjie.minbearwcs.utils.ContentPool;
import me.zhengjie.minbearwcs.utils.IdWorker;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
@RequiredArgsConstructor
public class ReworkGenerator implements MissionGenerator<String> {

    private final SmallStorageDao smallStorageDao;
    private final OutboundDao outboundDao;
    private final WcsMissionDao wcsMissionDao;
    private final IdWorker idWorker;
    private final ReworkOrderDetailDao reworkOrderDetailDao;
    private final StorageDao storageDao;
    private final LargeStorageDao largeStorageDao;

    @Override
    public MissionGenType type() {
        return MissionGenType.REWORK;
    }

    @Override
    public Tuple<String> generate(Object source) {
//        List<ReworkOrderDetail> reworkOrderDetailList = (List<ReworkOrderDetail>) source;
//
//        Set<String> needReworkSet = reworkOrderDetailList.stream()
//                .map(ReworkOrderDetail::getPalletCode)
//                .collect(Collectors.toSet());
//
//
//        HashSet<String> handlePalletSet = new HashSet<>();
//
//        for (ReworkOrderDetail reworkOrderDetail : reworkOrderDetailList) {
//            if (handlePalletSet.contains(reworkOrderDetail.getPalletCode())) continue;
//
//
//            SmallStorage smallStorage = smallStorageDao.selectByPallet(reworkOrderDetail.getPalletCode());
//            List<PalletMediumStorageSearchPo> palletMediumStorageSearchPoList = outboundDao.selectPalletMediumStorage(smallStorage.getMediumStorageCode());
//
//            String largeStorageCode = storageDao.selectLargeStorageCodeBySmallStorageCode(smallStorage.getSmallStorageCode());
//            LargeStorage largeStorage = largeStorageDao.selectByLargeStorageCode(largeStorageCode);
//
//
//            // 找个空中储位
//            Integer floorNum = largeStorage.getFloorNum();
//            String randomMediumStorage = null;
//            if (floorNum == 5) {
//                randomMediumStorage = storageDao.selectEmptyMediumStorageByStorageType(StorageType.STORAGE_AREA_5F);
//                if (randomMediumStorage == null) {
//                    randomMediumStorage = storageDao.selectEmptyMediumStorageByStorageType(StorageType.STORAGE_AREA_6F);
//                }
//            } else if (floorNum == 6) {
//                randomMediumStorage = storageDao.selectEmptyMediumStorageByStorageType(StorageType.STORAGE_AREA_6F);
//                if (randomMediumStorage == null) {
//                    randomMediumStorage = storageDao.selectEmptyMediumStorageByStorageType(StorageType.STORAGE_AREA_5F);
//                }
//            }
//
//            if (randomMediumStorage == null) {
//                return Tuple.tuple("没找到空闲储位存放无需返工的栈板", false);
//            }
//
//            if (randomMediumStorage != null) {
//                SmallStorage canUseSmallStorage = findSmallStorageInEmptyMediumStorage(randomMediumStorage);
//                if (smallStorage != null) {
//                    smallStorageDao.updateInboundFreezePallet(smallStorage.getId(), palletCode);
//                    mediumStorageDao.updateBatch1Info(randomMediumStorage, inboundOrder, materialCode, batchCode);
//                    return Tuple.tuple(smallStorage.getQrPoint(), true);
//                }
//            }
//
//            // 判断几个出口
//            long enterCount = palletMediumStorageSearchPoList.stream()
//                    .filter(a -> a.getIsEntrance() == 1)
//                    .count();
//
//
//            if (enterCount == 1) {
//                PalletMediumStorageSearchPo enter = palletMediumStorageSearchPoList.get(0);
//                if (enter.getIsEntrance() == 1) {
//                    // 从前往后
//                    List<OutboundStockUpRecord> resultList = new ArrayList<>();
//                    String lastWcsMisiionId = null;
//                    for (int i = 0; i < palletMediumStorageSearchPoList.size(); i++) {
//                        PalletMediumStorageSearchPo tempSingle = palletMediumStorageSearchPoList.get(i);
//                        if (tempSingle.getPalletCode() == null) continue;
//
//                        if (tempSingle.getOutboundFreezePallet() != null) {
//                            return Tuple.tuple("栈板: " + tempSingle.getPalletCode() + " , 正在出库，返工单下发失败", false);
//                        }
//
//                        if (needReworkSet.contains(tempSingle.getPalletCode())) {
//                            handlePalletSet.add(tempSingle.getPalletCode());
//
//                            ReworkOrderDetail handleDetail = getReworkOrderDetail(
//                                    reworkOrderDetailList,
//                                    tempSingle.getPalletCode()
//                            );
//
//
//                            // 生成有起点的任务
//                            reworkOrderDetailDao.updateStatusByDetailId(handleDetail.getReworkOrderDetailCode(), ReworkOrderDetailStatus.PROCESSING);
//                            reworkOrderDetailDao.updatePreWcsMissionIdByDetailId(handleDetail.getReworkOrderDetailCode(), lastWcsMisiionId);
//                            reworkOrderDetailDao.updateStartPointByDetailId(handleDetail.getReworkOrderDetailCode(), tempSingle.getSmallStorageCode());
//
//                            String missionId = "Task_Rework_Product_Line_" + idWorker.nextId();
//
//                            WcsMission wcsMission = new WcsMission(null, missionId, null, MissionType.REWORK_PRODUCT_LINE.name(),
//                                    ReworkProductLineStatus.WAIT_FOR_STORAGE.name(), LocalDateTime.now(), null, null,
//                                    1, handleDetail.getReworkOrderDetailCode());
//
//                            wcsMissionDao.insert(wcsMission);
//                            outboundTaskRecordDao.insert(outboundTaskRecord);
//
//
//                        } else {
//
//                        }
//
//                        resultList.add(
//                                new OutboundStockUpRecord(null, "stock_up_" + idWorker.nextId(), null, null,
//                                        tempSingle.getPalletCode(), tempSingle.getMaterialCode(), tempSingle.getMaterialNum(), floorNum, tempSingle.getSmallStorageCode(),
//                                        null, null, LocalDateTime.now())
//                        );
//                    }
//
//                    for (OutboundStockUpRecord lockPallet : resultList) {
//                        smallStorageDao.updateOutboundFreezeBySammStorageCode(lockPallet.getStartSmallStorage(), lockPallet.getPalletCode());
//                    }
//                    return Tuple.tuple(new MediumStockUp(resultList, needNum), true);
//                } else {
//                    // 从后往前
//                    if (isRest) {
//                        mediumStockUpTuple = searchBackToFrontRest(palletMediumStorageSearchPoList, floorNum, needNum);
//                    } else {
//                        mediumStockUpTuple = searchBackToFront(palletMediumStorageSearchPoList, floorNum, needNum);
//                    }
//
//                    if (mediumStockUpTuple.success) return mediumStockUpTuple;
//                }
//
//            } else {
//
//            }
//
//
//            // 是否全出
//            boolean isAllInMedium = true;
//            List<String> isAllInList = new ArrayList<>();
//            for (PalletMediumStorageSearchPo palletMediumStorageSearchPo : palletMediumStorageSearchPoList) {
//                if (palletMediumStorageSearchPo.getPalletCode() == null) continue;
//                if (palletMediumStorageSearchPo.getOutboundFreezePallet() != null) {
//                    isAllInMedium = false;
//                    break;
//                }
//                isAllInMedium &= needReworkSet.contains(palletMediumStorageSearchPo.getPalletCode());
//                isAllInList.add(palletMediumStorageSearchPo.getPalletCode());
//            }
//
//            if (isAllInMedium) {
//                handlePalletSet.addAll(isAllInList);
//                List<PalletMediumStorageSearchPo> collect = palletMediumStorageSearchPoList.stream()
//                        .filter(a -> isAllInList.contains(a.getPalletCode()))
//                        .collect(Collectors.toList());
//
//
//                // 生成有起点的任务
//                OutboundTaskRecord outboundTaskRecord = new OutboundTaskRecord(null, "outbound_record_" + idWorker.nextId(), null,
//                        null, smallStorage.getPalletCode(), null,
//                        null, null, smallStorage.getSmallStorageCode(), null, null,
//                        OutboundContentPool.OUTBOUND_RECORD_SORT, null, LocalDateTime.now(), null, pallet.getLogisticsCompanyCode());
//
//                String missionId = "Task_Outbound_Sort_after_" + idWorker.nextId();
//
//                WcsMission wcsMission = new WcsMission(null, missionId, null, MissionType.OUTBOUND_AFTER_SORT.name(),
//                        OutboundAfterSortMissionStatus.WAIT_FOR_STORAGE.name(), LocalDateTime.now(), null, null,
//                        1, outboundTaskRecord.getOutboundRecordId());
//                wcsMissionDao.insert(wcsMission);
//                outboundTaskRecordDao.insert(outboundTaskRecord);
//            }
//
//            // 不连续
//
//
//        }

        return null;
    }


    private ReworkOrderDetail getReworkOrderDetail(List<ReworkOrderDetail> reworkOrderDetailList, String palletCode) {
        return reworkOrderDetailList.stream()
                .filter(a -> a.getPalletCode().equals(palletCode))
                .findFirst()
                .orElse(null);
    }


    private SmallStorage findSmallStorageInEmptyMediumStorage(String mediumStorage) {
        List<SmallStorage> smallStorageList = smallStorageDao.selectSmallStorageByMediunStorage(mediumStorage);

        long outboundCount = smallStorageList.stream()
                .filter(a -> a.getOutboundFreezePallet() != null)
                .count();

        if (outboundCount > 0) return null;

        long enterCount = smallStorageList.stream()
                .filter(a -> a.getIsEntrance() == 1)
                .count();

        // 两口选最小
        if (enterCount == 2) {
            Optional<SmallStorage> optional = smallStorageList.stream()
                    .filter(a -> a.getInboundFreezePallet() == null)
                    .min(Comparator.comparingInt(SmallStorage::getColumnNum));

            if (optional.isPresent()) {
                return optional.get();
            }
        }

        // 一口选对侧
        if (enterCount == 1) {
            SmallStorage smallStorage = smallStorageList.get(0);
            if (smallStorage.getIsEntrance() == 1) {
                for (int i = smallStorageList.size() - 1; i >= 0; i--) {
                    SmallStorage temp = smallStorageList.get(i);
                    if (temp.getInboundFreezePallet() != null) continue;
                    return temp;
                }
                return smallStorageList.get(smallStorageList.size() - 1);
            } else {
                for (int i = 0; i < smallStorageList.size(); i++) {
                    SmallStorage temp = smallStorageList.get(i);
                    if (temp.getInboundFreezePallet() != null) continue;
                    return temp;
                }
            }
        }

        return null;
    }


}
